package com.yk.neon.lib.util.base.json;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.util.List;
import java.util.Map;

class GsonImpl {
	private static Gson gson = null;
	static {
		if (gson == null) {
			gson = new GsonBuilder().disableHtmlEscaping().create();
		}
	}

	private GsonImpl() {
	}

	/**
	 * 对象转成json
	 *
	 * @param object<dependency>
	 * 			<groupId>com.google.code.gson</groupId>
	 * 			<artifactId>gson</artifactId>
	 * 		</dependency>
	 * @return json
	 */
	static String gsonString(Object object) {
		String gsonString = null;
		if (gson != null) {
			gsonString = gson.toJson(object);
		}
		return gsonString;
	}

	/**
	 * 对象转成json,保留null值对象
	 *
	 * @param object
	 * @return json
	 */
	static String gsonStringIncludeNull(Object object) {
		String gsonString = null;
		Gson gson = new GsonBuilder().serializeNulls().disableHtmlEscaping().create();
		if (gson != null) {
			gsonString = gson.toJson(object);
		}
		return gsonString;
	}
	
	/**
	 * 对象转成json,保留null值对象,null转""
	 *
	 * @param object
	 * @return json
	 */
	static String gsonStringReplaceNull(Object object) {
		String gsonString = "";
		Gson gson = new GsonBuilder().serializeNulls().disableHtmlEscaping().create();
		if (gson != null) {
			gsonString = gson.toJson(object);
			gsonString.replaceAll("null", "\"\"");
		}
		return gsonString;
	}

	/**
	 * Json转成对象
	 *
	 * @param gsonString
	 * @param cls
	 * @return 对象
	 */
	static <T> T gsonToBean(String gsonString, Class<T> cls) {
		T t = null;
		if (gson != null) {
			t = gson.fromJson(gsonString, cls);
		}
		return t;
	}

	/**
	 * json转成list<T>
	 *
	 * @param gsonString
	 * @param cls
	 * @return list<T>
	 */
	static <T> List<T> gsonToList(String gsonString, Class<T> cls) {
		List<T> list = null;
		if (gson != null) {
			list = gson.fromJson(gsonString, new TypeToken<List<T>>() {
			}.getType());
		}
		return list;
	}

	/**
	 * json转成list中有map的
	 *
	 * @param gsonString
	 * @return List<Map<String, T>>
	 */
	static <T> List<Map<String, T>> gsonToListMaps(String gsonString) {
		List<Map<String, T>> list = null;
		if (gson != null) {
			list = gson.fromJson(gsonString, new TypeToken<List<Map<String, T>>>() {
			}.getType());
		}
		return list;
	}

	/**
	 * json转成map的
	 *
	 * @param gsonString
	 * @return Map<String, T>
	 */
	static <T> Map<String, T> gsonToMaps(String gsonString) {
		Map<String, T> map = null;
		if (gson != null) {
			map = gson.fromJson(gsonString, new TypeToken<Map<String, T>>() {
			}.getType());
		}
		return map;
	}
}
